package com.zeus.core.rule;

import com.zeus.common.enums.ZeusAlarmLevelEnum;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 聚合规则抽象类
 *
 * @author f1ybear_wang  2022/3/3 3:19 下午
 */
public abstract class AbstractGatherRule implements GatherRule {

    /**
     * 某段时间内累计发生次数
     */
    protected AtomicInteger count;

    /**
     * 开始发生时间-时间戳
     */
    protected Long startDate;

    /**
     * 最后发生时间-时间戳
     */
    protected Long lastDate;

    /**
     * 失败次数
     */
    protected AtomicInteger sendFailCount;

    /**
     * 发送成功次数
     */
    protected AtomicInteger sendSuccessCount;

    /**
     * 报警级别
     */
    protected ZeusAlarmLevelEnum levelEnum;

    public AbstractGatherRule() {
        count = new AtomicInteger(1);
        startDate = System.currentTimeMillis();
        lastDate = startDate;
        sendFailCount = new AtomicInteger(0);
        sendSuccessCount = new AtomicInteger(0);
        levelEnum = ZeusAlarmLevelEnum.P4;
    }

    @Override
    public void addCount() {
        this.count.incrementAndGet();
        this.lastDate = System.currentTimeMillis();
    }

    @Override
    public int getCount() {
        return this.count.get();
    }

    @Override
    public long continueTime() {
        return this.lastDate - this.startDate;
    }

    @Override
    public void addTaskBefore() {
        // 暂时未有操作
    }

    @Override
    public void addTaskAfter() {
        // 暂时未有操作
    }

    @Override
    public int getSendFailCount() {
        return this.sendFailCount.get();
    }

    @Override
    public ZeusAlarmLevelEnum alarmLevel() {
        return this.levelEnum;
    }

    @Override
    public void sendMessageSuccess() {
        this.sendSuccessCount.incrementAndGet();
        if (this.sendFailCount.get() > 0) {
            this.sendFailCount.decrementAndGet();
        }
    }

    @Override
    public void sendMessageFail() {
        this.sendFailCount.incrementAndGet();
    }
}
